document.addEventListener("DOMContentLoaded", function () {
  // 初始化地区数据
  let locations = [];
  // 获取DOM元素
  const locationNameInput = document.getElementById("locationName");
  const addLocationBtn = document.getElementById("addLocation");
  const locationsList = document.getElementById("locationsList");
  const locationsCount = document.getElementById("locationsCount");
  const adToggle = document.getElementById("adToggle");
  const adStatus = document.getElementById("adStatus");

  // 初始化广告状态
  initAdStatus();

  // 广告开关切换事件
  adToggle.addEventListener("change", function () {
    const isEnabled = this.checked;

    // 发起请求
    toggleAdDisplay(isEnabled)
      .then((response) => {
        if (response.success) {
          console.log(`广告已${isEnabled ? "开启" : "关闭"}`);
          updateAdStatus(isEnabled);
        } else {
          alert(`操作失败: ${response.message}`);
          // 回滚状态
          this.checked = !isEnabled;
          updateAdStatus(!isEnabled);
        }
      })
      .catch((error) => {
        console.error("请求失败:", error);
        alert("操作失败，请重试");
        // 回滚状态
        this.checked = !isEnabled;
        updateAdStatus(!isEnabled);
      });
  });

  // 添加地区
  addLocationBtn.addEventListener("click", function () {
    const name = locationNameInput.value.trim();

    if (name) {
      const newLocation = {
        id: Date.now(),
        name: name,
        active: true
      };

      locations.push(newLocation);
      saveLocations();
      // renderLocations();

      // 清空输入框
      locationNameInput.value = "";
    } else {
      alert("请输入地区名称");
    }
  });

  // 保存地区数据到
  function saveLocations() {
    console.log("saveLocations", locations);
    onSaveData(locations)
      .then((data) => {
        console.log(data);
      })
      .catch((err) => {
        console.error("saveLocations error", err);
        alert("修改失败");
      })
      .finally(() => {
        renderLocations();
      });
  }

  // 渲染地区列表
  function renderLocations() {
    // 更新计数
    locationsCount.textContent = `共${locations.length}个地区`;

    if (locations.length == 0) {
      locationsList.innerHTML = `
                  <li class="empty-state">
                      <svg width="64" height="41" viewBox="0 0 64 41" xmlns="http://www.w3.org/2000/svg">
                          <g transform="translate(0 1)" fill="none" fill-rule="evenodd">
                              <ellipse fill="#F5F5F5" cx="32" cy="33" rx="32" ry="7"></ellipse>
                              <g fill-rule="nonzero" stroke="#D9D9D9">
                                  <path d="M55 12.76L44.854 1.258C44.367.474 43.656 0 42.907 0H21.093c-.749 0-1.46.474-1.947 1.257L9 12.761V22h46v-9.24z"></path>
                                  <path d="M41.613 15.931c0-1.605.994-2.93 2.227-2.931H55v18.137C55 33.26 53.68 35 52.05 35h-40.1C10.32 35 9 33.259 9 31.137V13h11.16c1.233 0 2.227 1.323 2.227 2.928v.022c0 1.605 1.005 2.901 2.237 2.901h14.752c1.232 0 2.237-1.308 2.237-2.913v-.007z" fill="#FAFAFA"></path>
                              </g>
                          </g>
                      </svg>
                      <p>暂无地区数据，请添加新地区</p>
                  </li>
              `;
      return;
    }

    locationsList.innerHTML = "";

    locations.forEach((location) => {
      const li = document.createElement("li");
      li.className = "location-item";

      li.innerHTML = `
                  <div class="location-info">
                      <div class="location-name">${location.name}</div>
                      <div class="location-status ${
                        location.active ? "status-active" : "status-inactive"
                      }">
                          ${location.active ? "已启用" : "已禁用"}
                      </div>
                  </div>
                  <div class="location-actions">
                      <button class="btn-toggle ${
                        location.active ? "" : "inactive"
                      }" data-id="${location.id}">
                          ${location.active ? "禁用" : "启用"}
                      </button>
                      <button class="btn-delete" data-id="${
                        location.id
                      }">删除</button>
                  </div>
              `;

      locationsList.appendChild(li);
    });

    // 添加事件监听器
    document.querySelectorAll(".btn-toggle").forEach((btn) => {
      btn.addEventListener("click", function () {
        const id = parseInt(this.getAttribute("data-id"));
        toggleLocationStatus(id);
      });
    });

    document.querySelectorAll(".btn-delete").forEach((btn) => {
      btn.addEventListener("click", function () {
        const id = parseInt(this.getAttribute("data-id"));
        deleteLocation(id);
      });
    });
  }

  // 切换地区状态
  function toggleLocationStatus(id) {
    locations = locations.map((location) => {
      if (location.id == id) {
        return {
          ...location,
          active: !location.active
        };
      }
      return location;
    });

    saveLocations();
    // renderLocations();
  }

  // 删除地区
  function deleteLocation(id) {
    if (confirm("确定要删除这个地区吗？")) {
      locations = locations.filter((location) => location.id != id);
      saveLocations();
      // renderLocations();
    }
  }

  // 初始化广告状态
  function initAdStatus() {
    // 这里可以从服务器获取初始状态，这里先用本地存储模拟
    // const isEnabled = savedStatus ? JSON.parse(savedStatus) : false;
    // console.log(isEnabled);

    // updateAdStatus(false);
    onGetData().then((data) => {
      const showAD = data.showAD;
      adToggle.checked = showAD;
      locations = data.filter;
      updateAdStatus(showAD);
      renderLocations();
    });
  }

  // 更新广告状态显示
  function updateAdStatus(isEnabled) {
    adStatus.textContent = isEnabled ? "已开启" : "已关闭";
    adStatus.className = isEnabled ? "status-active" : "status-inactive";
  }

  // 切换广告展示状态的请求
  function toggleAdDisplay(enabled) {
    // 这里是模拟API请求，实际项目中替换为真实接口
    return new Promise((resolve) => {
      fetch("/api/admin/set-show?show=" + enabled)
        .then((response) => response.json())
        .then((resp) => {
          if (resp.code == 200) {
            resolve({
              success: true,
              message: enabled ? "广告已开启" : "广告已关闭"
            });
          }
        });
    });
  }

  // 初始渲染
  renderLocations();

  {
    // 获取新增的DOM元素
    const saveInitialAdBtn = document.getElementById("saveInitialAd");
    const saveRepeatAdBtn = document.getElementById("saveRepeatAd");

    // 初始化广告初始项和反复控制项
    initAdOptions();

    // 保存广告初始项
    saveInitialAdBtn.addEventListener("click", function () {
      const selectedOptions = getSelectedOptions("adInitial");
      saveAdOptions("initial", selectedOptions);
      console.log(selectedOptions);
    });

    // 保存反复控制项
    saveRepeatAdBtn.addEventListener("click", function () {
      const selectedOptions = getSelectedOptions("adRepeat");
      saveAdOptions("repeat", selectedOptions);
      console.log(selectedOptions);
    });
  }
  {
    const saveInfinityShowAdBtn = document.getElementById("saveInfinityShowAd");
    saveInfinityShowAdBtn.addEventListener("click", function () {
      const selectedOptions = getSelectedOptions("adInfinityShow");
      saveAdOptions("infinity", selectedOptions);
    });
    // 保存循环控制项延迟时间
    const saveInfinityShowDelayBtn = document.getElementById(
      "saveInfinityShowDelay"
    );
    saveInfinityShowDelayBtn.addEventListener("click", function () {
      const delay = document.getElementById("infinityShowDelay").value;
      saveAdOptions("infinityDelay", delay);
    });
  }
});

// 获取数据
function onGetData() {
  return fetch("/api/admin/data")
    .then((response) => response.json())
    .then((resp) => {
      if (resp.code == 200) {
        return resp.data;
      }
      return Promise.reject(resp.message);
    });
}

// 保存城市列表
function onSaveData(data) {
  return axios.post("/api/admin/save-city", data).then((resp) => {
    if (resp.data.code == 200) {
      return resp.data.data;
    }
    return Promise.reject(resp.data.message);
  });
}

// *************************

// 初始化广告选项
function initAdOptions() {
  // 这里可以从服务器获取初始选项状态
  // 模拟数据
  // const initialOptions = ["banner", "video"];
  // const repeatOptions = ["interstitial"];
  axios.get("/api/admin/ad-init").then((resp) => {
    if (resp.data.code == 200) {
      const data = resp.data.data;
      const initialOptions = data.initial.split(",");
      const repeatOptions = data.repeat.split(",");
      setSelectedOptions("adInitial", initialOptions);
      setSelectedOptions("adRepeat", repeatOptions);
      setSelectedOptions("adInfinityShow", data.infinity.split(","));
      document.getElementById("infinityShowDelay").value = data.infinityDelay;
    }
  });
}

// 获取选中的选项
function getSelectedOptions(name) {
  const checkboxes = document.querySelectorAll(`input[name="${name}"]:checked`);
  return Array.from(checkboxes).map((checkbox) => checkbox.value);
}

// 设置选中的选项
function setSelectedOptions(name, values) {
  const checkboxes = document.querySelectorAll(`input[name="${name}"]`);
  checkboxes.forEach((checkbox) => {
    checkbox.checked = values.includes(checkbox.value);
  });
}

// 保存广告选项
function saveAdOptions(type, options) {
  // console.log(
  //   `保存${type === "initial" ? "广告初始项" : "反复控制项"}:`,
  //   options
  // );

  // 这里可以发送请求到服务器保存设置
  axios
    .post(`/api/admin/ad-set`, { [type]: options })
    .then((response) => {
      if (response.data.code === 200) {
        // alert("保存成功");
      } else {
        alert("保存失败: " + response.data.message);
      }
    })
    .catch((error) => {
      console.error("保存失败:", error);
      alert("保存失败，请重试");
    })
    .finally(() => {
      initAdOptions();
    });
}
